package com.gamota.mobi;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.androidquery.AQuery;

import com.easy.facebook.android.apicall.GraphApi;
import com.easy.facebook.android.facebook.FBLoginManager;
import com.easy.facebook.android.facebook.Facebook;
import com.easy.facebook.android.facebook.LoginListener;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.event.Event.UserInfoFailEvent;
import com.gamota.mobi.network.ProgressDialogManager;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.Utils;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class PostFacebookActivity extends SherlockActivity implements LoginListener, OnClickListener {
	
	private AQuery aq;
	private String FB_APP_ID;
	private FBLoginManager fbLoginManager;
	private static final int FB_REQUEST_CODE = 69;
	private String ids = "";
	private String names = "";
	private String urlPicture;
	private String name;
	private String link;
	private Facebook facebook;
	private ProgressDialog pDialog;
	private String message;
	private BackgroundTasks bgTask;
	//private Giftbox giftbox;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_post_fb);
		aq = new AQuery(this);
		bgTask = new BackgroundTasks(this);
		message = getIntent().getStringExtra(Constants.SHARE_MESSAGE);
//		if(!TextUtils.isEmpty(message)){
//			getUserInfo();
//		}
		aq.id(R.id.btn_post).clicked(this);
		urlPicture = getIntent().getStringExtra(Constants.SHARE_PICTURE);
		name = getIntent().getStringExtra(Constants.SHARE_NAME);
		link = getIntent().getStringExtra(Constants.SHARE_LINK);
		konnectFacebook();
		aq.id(R.id.btn_tag_friends).clicked(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(PostFacebookActivity.this, FBFriendListActivity.class);
				startActivityForResult(i, FB_REQUEST_CODE);
			}
		});
	}
	
//	private void getUserInfo(){
//		String accessToken = Utils.getStaticAccessToken(this);
//		bgTask.getUserInfo(accessToken);
//	}
	
//	public void onEventMainThread(UserInfoSuccessEvent e){
//		if(!TextUtils.isEmpty(message)){
//			String username = e.getUser().getFullName();
//			if(TextUtils.isEmpty(username)){
//				username = e.getUser().getUserName();
//			}
//			message = username + " " + message;
//			aq.id(R.id.edit_post_msg).text(message).enabled(false);
//		}
//	}
	
	public void onEventMainThread(UserInfoFailEvent e){
		if(!TextUtils.isEmpty(message)){
			message = getResources().getString(R.string.me) + " " + message;
			aq.id(R.id.edit_post_msg).text(message).enabled(false);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}
	
	private void konnectFacebook(){
		String permissions[] = {"email", "read_stream","publish_stream", "read_friendlists"};
		FB_APP_ID = getResources().getString(R.string.fb_app_id);
		fbLoginManager = new FBLoginManager(this, R.layout.activity_login, FB_APP_ID, permissions);
		if(fbLoginManager.existsSavedFacebook()){
			fbLoginManager.loadFacebook();
		} else {
			fbLoginManager.login();
		}
	}

	@Override
	public void loginSuccess(Facebook facebook) {
		// TODO Auto-generated method stub
		this.facebook = facebook;
		final GraphApi graph = new GraphApi(facebook);
			if(!TextUtils.isEmpty(message)){
				pDialog = ProgressDialogManager.showProgressDialog(PostFacebookActivity.this, R.string.loading);
				AsyncExecutor.create().execute(new RunnableEx() {
					@Override
					public void run() throws Exception {
						// TODO Auto-generated method stub
						String userName = graph.getMyAccountInfo().getFirst_name() + " " + graph.getMyAccountInfo().getLast_name();
						EventBus.getDefault().post(userName);
					}
				});
			}
	}
	
	public void onEventMainThread(String userName){
		if(pDialog.isShowing()){
			pDialog.dismiss();
		}
		message = userName + " " + message;
		aq.id(R.id.edit_post_msg).text(message).enabled(false);
	}
	
	public void onEventMainThread(PostEvent e){
		if(pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(e.getPostId() != null){
			Toast.makeText(this, R.string.share_success, Toast.LENGTH_SHORT).show();
			String accessToken = Utils.getStaticAccessToken(this);
			bgTask.reportGiftbox(accessToken, getIntent().getStringExtra(Constants.SLUG), "confirm", getIntent().getStringExtra(Constants.PACKAGE_NAME));
		} else {
			Toast.makeText(this, R.string.share_fail, Toast.LENGTH_SHORT).show();
		}
		finish();
	}
	
//	public void onEventMainThread(CreateUserSettingFail e){
//		Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//		String content = gson.toJson(giftbox, Giftbox.class);
//		String accessToken = Utils.getStaticAccessToken(this);
//		bgTask.createUserSetting(accessToken, "gift" + giftbox.getSlug().replace("-", "").trim(), content, 1);
//	}
//	
//	public void onEventMainThread(ReportGiftboxFail e){
//		String accessToken = Utils.getStaticAccessToken(this);
//		bgTask.reportGiftbox(accessToken, getIntent().getStringExtra(Constants.SLUG), "confirm");
//	}
	
	private static class PostEvent {
		public String getPostId() {
			return postId;
		}

		String postId;

		public PostEvent(String postId) {
			this.postId = postId;
		}
	}

	@Override
	public void logoutSuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void loginFail() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == FB_REQUEST_CODE && resultCode == RESULT_OK){
			ids = data.getStringExtra(Constants.FB_USER_IDS);
			names = data.getStringExtra(Constants.FB_USER_NAMES);
			if(!TextUtils.isEmpty(names)){
				aq.id(R.id.text_tags).visible().text(names);
			} else {
				aq.id(R.id.text_tags).gone();
			}
		} else if(requestCode == FB_REQUEST_CODE && resultCode == RESULT_CANCELED){
			
		} else {
			if(fbLoginManager!=null&&data!=null){
				if(data.hasExtra("expires_in")&&data.hasExtra("access_token")){
					fbLoginManager.loginSuccess(data);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_post:
			final GraphApi graph = new GraphApi(facebook);
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			AsyncExecutor.create().execute(new RunnableEx() {
				@Override
				public void run() throws Exception {
					// TODO Auto-generated method stub
					String postId;
					if(TextUtils.isEmpty(ids)){
						postId = graph.setStatus(aq.id(R.id.edit_post_msg).getText().toString(), null, urlPicture, null, null, link, name);
					} else {
						postId = graph.setStatus(aq.id(R.id.edit_post_msg).getText().toString(), ids, urlPicture, null, null, link, name);
					}
					EventBus.getDefault().post(new PostEvent(postId));
				}
			});
			break;
		default:
			break;
		}
	}
}
